Lab 11 - Interactive Visualization
Learning Goals
- Read in and process the COVID dataset from the New York Times GitHub repository
- Create interactive graphs of different types using
plot_ly()andggplotly()functions - Customize the hoverinfo and other plot features
- Create a Choropleth map using
plot_geo()
Lab Description
We will work with COVID data downloaded from the New York Times. The dataset consists of COVID-19 cases and deaths in each US state during the course of the COVID epidemic.
The objective of this lab is to explore relationships between cases, deaths, and population sizes of US states, and plot data to demonstrate this
Steps
I. Reading and processing the New York Times (NYT) state-level COVID-19 data
0. Install and load libraries
library(data.table)
library(tidyverse)## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.0 ✔ purrr 1.0.1
## ✔ tibble 3.1.8 ✔ dplyr 1.0.10
## ✔ tidyr 1.2.1 ✔ stringr 1.5.0
## ✔ readr 2.1.3 ✔ forcats 0.5.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::between() masks data.table::between()
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::first() masks data.table::first()
## ✖ dplyr::lag() masks stats::lag()
## ✖ dplyr::last() masks data.table::last()
## ✖ purrr::transpose() masks data.table::transpose()
library(plotly)##
## Attaching package: 'plotly'
##
## The following object is masked from 'package:ggplot2':
##
## last_plot
##
## The following object is masked from 'package:stats':
##
## filter
##
## The following object is masked from 'package:graphics':
##
## layout
library(knitr)
library(widgetframe)## Loading required package: htmlwidgets
1. Read in the data
- Read in the COVID data with data.table:fread() from the NYT GitHub repository: “https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv”
- Read in the state population data with data.table:fread() from the repository: “https://raw.githubusercontent.com/COVID19Tracking/associated-data/master/us_census_data/us_census_2018_population_estimates_states.csv””
- Merge datasets
cv_states_readin <-
data.table::fread("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
state_pops <- data.table::fread("https://raw.githubusercontent.com/COVID19Tracking/associated-data/master/us_census_data/us_census_2018_population_estimates_states.csv")
state_pops$abb <- state_pops$state
state_pops$state <- state_pops$state_name
state_pops$state_name <- NULL
cv_states <- merge(cv_states_readin, state_pops, by="state")2. Look at the data
- Inspect the dimensions,
head, andtailof the data - Inspect the structure of each variables. Are they in the correct format?
dim(cv_states)
head(cv_states)
tail(cv_states)
str(cv_states)3. Format the data
- Make date into a date variable
- Make state into a factor variable
- Order the data first by state, second by date
- Confirm the variables are now correctly formatted
- Inspect the range values for each variable. What is the date range? The range of cases and deaths?
cv_states$date <- as.Date(cv_states$date, format="%Y-%m-%d")
state_list <- unique(cv_states$state)
cv_states$state <- factor(cv_states$state, levels = state_list)
abb_list <- unique(cv_states$abb)
cv_states$abb <- factor(cv_states$abb, levels = abb_list)
cv_states = cv_states[order(cv_states$state, cv_states$date),]str(cv_states)
head(cv_states)
tail(cv_states)
head(cv_states)
summary(cv_states)
min(cv_states$date)
max(cv_states$date)Answer: The date range is from 2020-03-13 to 2023-03-21. The cases range is 1 to 12,154,941, and the deaths range is 0 to 104,185 .
4. Add new_cases and new_deaths and
correct outliers
- Add variables for new cases,
new_cases, and new deaths,new_deaths:- Hint: You can set
new_casesequal to the difference between cases on date i and date i-1, starting on date i=2
- Hint: You can set
new_cv_states <- cv_states %>%
group_by(state) %>%
mutate(
new_cases = c(-9999, diff(cases)),
new_deaths = c(-9999, diff(deaths))
) %>%
mutate(
new_cases = ifelse(new_cases == -9999, cases, new_cases),
new_deaths = ifelse(new_deaths == -9999, deaths, new_deaths)
)- Filter to dates after October 1, 2022
time_cv_states <- new_cv_states %>% filter(date >= '2022-10-01')- Use
ggplotlyfor EDA: See if there are outliers or values that don’t make sense fornew_casesandnew_deaths. Which states and which dates have strange values?
plt_case <- ggplot(
time_cv_states, aes(x = date, y = new_cases, colour = state)) +
geom_line() +
theme_bw() +
ggtitle("New cases in the US since 2022-10-01")
ggplotly(plt_case)plt_death <- ggplot(
time_cv_states, aes(x = date, y = new_deaths, colour = state)) +
geom_line() +
theme_bw() +
ggtitle("New deaths in the US since 2022-10-01")
ggplotly(plt_death)Answer: There are a few negative values for both new_cases and new deaths, which is definitely not possible. For example, Tennesse on 2023-01-01, this is likely due to errors in data. Also, new york has some extremely high new deaths on 2022-11-11, which seems abnormal.
Correct outliers: Set negative values for
new_casesornew_deathsto 0Inspect data again interactively
time_cv_states <- time_cv_states %>% mutate(
new_cases = ifelse(new_cases < 0, 0, new_cases),
new_deaths = ifelse(new_deaths < 0, 0, new_deaths)
)5. Add additional variables
Add population-normalized (by 100,000) variables for each variable type (rounded to 1 decimal place). Make sure the variables you calculate are in the correct format (
numeric). You can use the following variable names:per100k= cases per 100,000 populationnewper100k= new cases per 100,000deathsper100k= deaths per 100,000newdeathsper100k= new deaths per 100,000
Add a “naive CFR” variable representing
deaths / caseson each date for each stateCreate a dataframe representing values on the most recent date,
cv_states_today
per100_cv_states <- time_cv_states %>%
mutate(
per100k = round(cases / population * 1e5, digits = 1),
newper100k = round(new_cases / population * 1e5, digits = 1),
deathsper100k = round(deaths / population * 1e5, digits = 1),
newdeathsper100k = round(new_deaths / population * 1e5, digits = 1)
)cfr_states <- per100_cv_states %>% mutate(
naive_cfr = deaths / cases
)max_date <- max(cfr_states$date)
cv_states_today <- cfr_states %>% filter(date == max_date)II. Scatterplots
6. Explore scatterplots using plot_ly()
- Create a scatterplot using
plot_ly()representingpop_densityvs. various variables (e.g.cases,per100k,deaths,deathsper100k) for each state on most recent date (cv_states_today)- Color points by state and size points by state population
- Use hover to identify any outliers.
plot_ly(
cv_states_today,
x = ~log(pop_density),
y = ~per100k,
color = ~state,
size = ~population,
type = "scatter",
sizes = c(5, 100),
marker = list(sizemode = "diameter", opacity = 0.8)
) %>% layout(title = "Cases per 100k vs state population ")- Remove those outliers and replot.
# Removing District of Columbia
plot_ly(
cv_states_today %>% filter(state != "District of Columbia"),
x = ~pop_density,
y = ~per100k,
color = ~state,
size = ~population,
type = "scatter",
sizes = c(5, 100),
marker = list(sizemode = "diameter", opacity = 0.8)
) %>% layout(title = "Cases vs state population without District of Columbia")- Choose one plot. For this plot:
- Add hoverinfo specifying the state name, cases per 100k, and deaths per 100k, similarly to how we did this in the lecture notes
- Add layout information to title the chart and the axes
- Enable
hovermode = "compare"
plot_ly(
cv_states_today,
x = ~log(pop_density),
y = ~cases,
color = ~state,
size = ~population,
type = "scatter",
sizes = c(5, 50),
marker = list(sizemode = "diameter",
opacity = 0.8),
hoverinfo = "text",
text = ~ paste0(state, "\n", " Cases per 100k: ", per100k, "\n",
" Deaths per 100k: ", deathsper100k, "\n",
" Population density: ", round(pop_density, 1), " per sq miles")
) %>% layout(title = "Cumulative cases vs log population density",
hovermode = 'x')7. Explore scatterplot trend interactively using
ggplotly() and geom_smooth()
- For
pop_densityvs.newdeathsper100kcreate a chart with the same variables usinggglot_ly() - Explore the pattern between \(x\) and \(y\)
- Explain what you see. Do you think
pop_densitycorrelates withnewdeathsper100k?
plt_smooth <- ggplot(
cv_states_today,
aes(x = pop_density, y = newdeathsper100k)) +
geom_point(aes(color = state, size = population)) +
geom_smooth() +
theme_minimal() +
scale_x_continuous(trans = "log") +
ylab("new deaths per 100k") +
xlab("population density")
ggplotly(plt_smooth)Answer: It seems like that population density isn’t correlated with new deaths per 1000 population, since the fitted line is almost flat, and we don’t see any distinct trends in the points as well.
8. Multiple line chart
- Create a line chart of the
naive_CFRfor all states over time usingplot_ly()- Use the zoom and pan tools to inspect the
naive_CFRfor the states that had an increase in September. How have they changed over time?
- Use the zoom and pan tools to inspect the
plot_ly(
cfr_states,
x = ~date,
y = ~naive_cfr,
color = ~ state,
mode = "lines"
) %>% layout(hovermode = "x unified") # added for better comparison- Create one more line chart, for Florida only, which shows
new_casesandnew_deathstogether in one plot. Hint: useadd_layer()
# I think you were just missing a type = "scatter" for it to work
plot_ly(
cfr_states %>% filter(state == "Florida"),
x = ~ date,
y = ~ new_cases,
type = "scatter",
mode = "linear",
name = "cases"
) %>% add_trace(
y = ~new_deaths,
name = "deaths")- Use hoverinfo to “eyeball” the approximate peak of deaths and peak of cases. What is the time delay between the peak of cases and the peak of deaths?
Answer: It seems that the peak of deaths and peak of cases has a lag of 0. For example there’s a peak of cases on Jan 6th, and a peak of deaths of 264 deaths on Jan 6th as well. Almost all the peaks of cases and deaths match.
9. Heatmaps
Create a heatmap to visualize new_cases for each state
on each date greater than January 1st, 2023 - Start by mapping selected
features in the dataframe into a matrix using the tidyr
package function pivot_wider(), naming the rows and
columns, as done in the lecture notes - Use plot_ly() to
create a heatmap out of this matrix. Which states stand out?
cv_states_mat <- cfr_states %>% select(state, date, new_cases) %>%
pivot_wider(names_from = state, values_from = new_cases) %>%
column_to_rownames("date")
cv_states_mat %>%
plot_ly(
x = rownames(cv_states_mat),
y = colnames(cv_states_mat),
z = ~as.matrix(cv_states_mat),
type = "heatmap",
showscale = TRUE
)Answer: It seems like Virginia, Washington, North Dakata had very high new cases, and a lot of them is on the date Oct 5, 2022.
- Create a second heatmap in which the pattern of
new_casesfor each state over time becomes more clear by filtering to only look at dates every two weeks.
#create heatmap
filter_dates <- seq(
as.Date("2022-10-01"),
max_date,
by = "3 days"
)
cv_states_mat2 <- cfr_states %>% select(state, date, new_cases) %>%
filter(date %in% filter_dates) %>%
pivot_wider(names_from = state, values_from = new_cases) %>%
column_to_rownames("date")
cv_states_mat2 %>%
plot_ly(
x = rownames(cv_states_mat2),
y = colnames(cv_states_mat2),
z = ~as.matrix(cv_states_mat2),
type = "heatmap",
showscale = TRUE
)10. Map
- Create a map to visualize the
naive_CFRby state on March 15, 2023
pick.date = "2023-03-15"
# Create the map
cv_march_15 <- cfr_states %>%
filter(date == pick.date)
plot_geo(cv_march_15,
locationmode = "USA-states") %>%
add_trace(
z = ~naive_cfr,
locations = ~abb
) %>%
layout(
geo = list(
scope = "usa",
showlakes = TRUE,
lakecolor = toRGB("red")
)
)- Compare with a map visualizing the
naive_CFRby state on most recent date
# Map for today's date
plot_geo(cv_states_today,
locationmode = "USA-states") %>%
add_trace(
z = ~naive_cfr,
locations = ~abb
) %>%
layout(
geo = list(
scope = "usa",
showlakes = TRUE,
lakecolor = toRGB("red")
)
)